﻿using System.Collections.Generic;
using System.Linq;

namespace HF.Repository
{
    public class PagedList<T> : List<T>, IPagedList
    {
        public PagedList()
            : this(new T[0], 1, 10, 0)
        {
        }

        public PagedList(IEnumerable<T> source, int index, int pageSize)
            : this(source.Skip((index - 1)*pageSize).Take(pageSize), index, pageSize, source.Count())
        {
        }

        public PagedList(IEnumerable<T> source, int index, int pageSize, int totalCount)
            : base(source)
        {
            if (index < 1)
                index = 1;
            PageSize = pageSize;
            PageIndex = index;

            TotalCount = totalCount;

            TotalPages = TotalCount/PageSize;

            if (0 < TotalCount%PageSize)
                ++TotalPages;
        }

        #region IPagedList Members

        public int TotalPages { get; private set; }

        public int TotalCount { get; set; }

        public int PageIndex { get; set; }

        public int PageSize { get; set; }

        public bool HasPreviousPage
        {
            get { return PageIndex > 1; }
        }

        public bool HasNextPage
        {
            get { return PageIndex < TotalPages; }
        }

        #endregion
    }

    public static class Pagination
    {
        public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int index, int pageSize, int totalCount)
        {
            return new PagedList<T>(source.ToArray(), index, pageSize, totalCount);
        }

        public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int index, int pageSize)
        {
            return new PagedList<T>(source, index, pageSize);
        }

        public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int index)
        {
            return new PagedList<T>(source, index, 10);
        }
    }
}